//
//  LeftController.m
//  gdemm
//
//  Created by 乔明超 on 16/9/23.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "LeftController.h"
#import "SetTableViewCell.h"
#import "SliderController.h"
#import "LoginController.h"
#import "Masonry.h"
#import "HeartBeat.h"
#import "PolicyManager.h"
#import "AboutViewController.h"
#import "PersonalInforViewController.h"
#import "Utils.h"
#import "QrCodeController.h"
static NSString *const reUse = @"reUse";
@interface LeftController ()<UITableViewDelegate, UITableViewDataSource,UITextViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray <NSArray *>*dataArray;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIView *headView;
@property (nonatomic, strong) UITextView *policyInfoTV;
@property (nonatomic, strong) UIWindow *policyInfoWindow;

@end

@implementation LeftController

static NSString *identifier = @"setting";

#pragma mark - headerView


- (UITextView *)policyInfoTV{
    if (_policyInfoTV == nil) {
        _policyInfoTV = [[UITextView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        _policyInfoTV.backgroundColor = [UIColor whiteColor];
        [_policyInfoTV setEditable:YES];
        [_policyInfoTV setDelegate:self];
        [self.policyInfoWindow addSubview:_policyInfoTV];
    }
    
    return _policyInfoTV;
}

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    return NO;
}


- (UIWindow *)policyInfoWindow{
    if (_policyInfoWindow == nil) {
        _policyInfoWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeWindowHandler:)];
        tap.numberOfTapsRequired = 1;
        tap.numberOfTouchesRequired = 2;
        [_policyInfoWindow addGestureRecognizer:tap];
    }
    return _policyInfoWindow;
}
- (UIView *)headView{
    if (!_headView) {
        _headView = [[UIView alloc]init];
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.image = [Utils getImageByDevce:@"sliderBar_top_icon"];
        [_headView addSubview:imageView];
        
        if (![DeviceTypeJudge isPadDeviceType]) {
            _headView.frame = CGRectMake(0, 0, kLeftWidthScale*kScreenWidth, 130*KHeightScale);
            [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(_headView);
                make.bottom.mas_equalTo(_headView.bottom).offset(-30*KHeightScale);
                make.width.mas_equalTo(104*KWidthScale);
                make.height.mas_equalTo(35*KHeightScale);
            }];
        }else{
            _headView.frame = CGRectMake(0, 0, kLeftWidthScale*kScreenWidth, 300);
            [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.mas_equalTo(_headView);
                make.width.mas_equalTo(168);
                make.height.mas_equalTo(54);
            }];
        }
    }
    
    return _headView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(skinSwitchHandler) name:@"skinswitch" object:nil];
    self.view.backgroundColor = [Utils colorWithKey:@"leftBgColor"];
    //@[[Utils getImageByDevce:@"siderBar_scan"], NSLocalizedString(@"str_scan", @"扫码")],
    self.dataArray = @[@[[Utils getImageByDevce:@"siderBar_info"], NSLocalizedString(@"str_person_info", @"个人信息")],
                       @[[Utils getImageByDevce:@"siderBar_update"], NSLocalizedString(@"str_policy_update", @"策略更新")],
                       @[[Utils getImageByDevce:@"siderBar_about"], NSLocalizedString(@"str_about", @"关于")],
                       @[[Utils getImageByDevce:@"siderBar_exit"], NSLocalizedString(@"str_exit", @"退出")]];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kLeftWidthScale*kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.scrollEnabled = NO;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.tableHeaderView = self.headView;
    _tableView.tableFooterView = [[UIView alloc] init];
    [self getPolicyInfo];
}


#pragma mark - tableView procotol methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[SetTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.titleLable.text = self.dataArray[indexPath.row][1];
    cell.imgView.image = self.dataArray[indexPath.row][0];
    cell.lineView.backgroundColor = [Utils colorWithKey:@"leftCellLineColor"];
    
    return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (![DeviceTypeJudge isPadDeviceType]) {
        return 47*KHeightScale;
    }
    return 72;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SliderController * sliderVc = [SliderController sharedInstance];
    if (indexPath.row == 2) {
        UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"AboutStoryBoard" bundle:nil];
        AboutViewController * aboutVc = [storyBoard instantiateInitialViewController];
        [sliderVc.navigationController pushViewController:aboutVc animated:YES];
    }else if(indexPath.row == 3){
        [self offline];
    }else if(indexPath.row == 0){
        PersonalInforViewController * personalInfoVc = [[PersonalInforViewController alloc]init];
        [sliderVc.navigationController pushViewController:personalInfoVc animated:YES];
    }if (indexPath.row == 1) {
        [[PolicyManager getInstance]updatePolicyWithsilent:NO];
    }
//    if(indexPath.row == 2){
//        if ([self checkAVAuthorizationStatus]) {
//            QrCodeController * qrCodeVc = [[QrCodeController alloc]init];
//            [sliderVc.navigationController pushViewController:qrCodeVc animated:YES];
//        }else{
//            UIAlertController * alertVc = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"str_unUseCamera", @"无法使用相机") message:nil preferredStyle:UIAlertControllerStyleAlert];
//            UIAlertAction * action = [UIAlertAction actionWithTitle:NSLocalizedString(@"str_ok", @"确定") style:UIAlertActionStyleDefault handler:nil];
//            [alertVc addAction:action];
//            [self presentViewController:alertVc animated:YES completion:nil];
//        }
//       
//    }

}

- (BOOL)checkAVAuthorizationStatus
{
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(status == AVAuthorizationStatusRestricted) {
        return NO;
    } else {
        return  YES;
    }
}

//用户退出离线
/*用户离线*/
- (void)offline{
    [[HeartBeat shareInstance]offline];
    UIWindow *window =[UIApplication sharedApplication].delegate.window;
    window.rootViewController = nil;
    LoginController *loginVc = [[LoginController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVc];
    window.rootViewController = nav;
}


- (void)getPolicyInfo{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addViewHandler:)];
    tap.numberOfTapsRequired = 8;
    [self.view addGestureRecognizer:tap];
}

- (void)addViewHandler:(UITapGestureRecognizer *)tap{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *dir = [paths[0] stringByAppendingPathComponent:@"config"];
    
    NSString *filePath = [dir stringByAppendingPathComponent:@"policies.json"];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
    NSMutableString *policyInfo = [NSMutableString string];
    
    [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        [policyInfo appendString:@"\n"];
        if (obj == nil || [(NSDictionary *)obj count] == 0) {
           
            [policyInfo appendString:[NSString stringWithFormat:@"%@\n",key]];
        }else{
        
            [policyInfo appendString:[NSString stringWithFormat:@"%@:%@\n",key,obj]];
        }
    }];
    self.policyInfoWindow.hidden = NO;
    self.policyInfoTV.text = policyInfo;
    
}

- (void)removeWindowHandler:(UITapGestureRecognizer *)tap{
    self.policyInfoWindow.hidden = YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 *  切换肤色
 */

- (void)skinSwitchHandler{
    self.view.backgroundColor = [Utils colorWithKey:@"leftBgColor"];
    [self.tableView reloadData];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
